package cn.dnf.filters;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

public class LoginCheckFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return null;
    }
    //filter执行时机，数字越小越先执行，不要弄成负数
    @Override
    public int filterOrder() {
        return 0;
    }

    //此方法用来判断是否要执行目标业务方法的，比如登录校验就是判断当前请求是否需要校验
    @Override
    public boolean shouldFilter() {
        //1.得到上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //2.得到请求的uri
        String uri = currentContext.getRequest().getRequestURI();
        //3.判断是否包含login/
        if (uri.endsWith("login") || uri.endsWith("register")){
            return false;
        }

        return true;
    }
    //执行目标业务方法的，是否调用取决于shouldFilter的返回值是否为true
    @Override
    public Object run() throws ZuulException {
        //1.得到token
        String token = RequestContext.getCurrentContext().getRequest().getHeader("token");
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //设置响应数据的格式和编码
        response.setContentType("application/json;charset=utf-8");
        if(StringUtils.isEmpty(token)){
            try {
                HashMap<String, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","noLogin");
                PrintWriter writer = response.getWriter();
                //利用fastjson转换map对象
                String strJson = JSONObject.toJSONString(map);
                writer.write(strJson);
                // 2.阻止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);



            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 如果要放行，这里返回null即可，不用管
        return null;
    }
}
